package com.xxgc.demo.utils;
/*
 *
 *   @Author:SJY
 *   @Date: 2023/9/27-09-27-16:02
 *   任务调度工具类
 */

import org.quartz.*;
import org.quartz.impl.StdSchedulerFactory;

public class SchedulerUtil {

    private Scheduler scheduler;
    private Trigger trigger;
    private JobDetail jobDetail;

    private SchedulerUtil(Scheduler scheduler) {
        this.scheduler = scheduler;
    }

    public static SchedulerUtil create() throws SchedulerException {
        return new SchedulerUtil(StdSchedulerFactory.getDefaultScheduler());
    }

    public SchedulerUtil withTrigger(String name, String group, String cronExpression) {
        this.trigger = TriggerBuilder.newTrigger()
                .withIdentity(name, group)
                .withSchedule(CronScheduleBuilder.cronSchedule(cronExpression))
                .startNow()
                .build();
        return this;
    }

    public SchedulerUtil withJob(String name, String group, Class<? extends Job> jobClass) {
        this.jobDetail = JobBuilder.newJob(jobClass)
                .withIdentity(name, group)
                .build();
        return this;
    }

    public void schedule() throws SchedulerException {
        if (trigger == null || jobDetail == null) {
            throw new IllegalStateException("Trigger and JobDetail must be set before scheduling.");
        }
        scheduler.scheduleJob(jobDetail, trigger);
        scheduler.start();
    }
}
